<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="机构" prop="departmentId">
        <el-select
          v-model="queryParams.departmentId"
          placeholder="请选择机构"
          filterable
          clearable
        >
          <el-option
            v-for="item in departmentList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="diy-mb-5">
      <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['admin:road:create']">新增</el-button>
      <el-button type="primary" plain icon="el-icon-download" size="mini"
        @click="handleExport"  v-hasPermi="['system:spparkplacecode:export']">全部导出</el-button>
        <el-button type="primary" plain size="mini"
        @click="handleExportList" v-hasPermi="['system:spparkplacecode:export']">查看导出列表</el-button>
    </div>

    <el-table v-loading="loading" :data="spparkplaceList" >
      <el-table-column
      v-for="(item,index) in tableList"
      :key="index"
      :label="item.label" align="center" :prop="item.prop" :width="item.width ? item.width : ''">
        <template
        slot-scope="{row}">
          <dict-tag v-if="item.prop == 'status'" :options="dict.type.EBerthQrcodeStatus" :value="row[item.prop]"/>
          <div v-else>{{row[item.prop]}}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="240">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            plain
            @click="handleEwmShow(scope.row)"
          >查看二维码
          </el-button>
          <el-button
            size="mini"
            type="primary"
            plain
            @click="handleUnbind(scope.row)"
            v-hasPermi="['admin:road:setOnline']"
            v-if="scope.row.berthCode"
          >解绑
          </el-button>
          <el-button
            size="mini"
            type="primary"
            plain
            @click="handleBind(scope.row)"
            v-hasPermi="['admin:road:setOnline']"
            v-if="!scope.row.berthCode"
          >关联车位号
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改车位信息对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" :width="title == '查看二维码' ? '20%' : '1000px'" append-to-body>
      <div v-if="title == '查看二维码'">
        <div >
          <div id="qrcode"></div>
        </div>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="108px" v-else>
        <el-row v-if="title == '关联车位号'">
          <el-col :span="24">
            <el-form-item label="泊位" prop="berthId">
              <el-select ref="bowei" v-model="form.berthId" clearable
              remote
              v-loadMore="loadMore"
              :remote-method="remoteMethod"
              :loading="bwLoddng"
              filterable  placeholder="请选择出入口">
                <el-option
                  v-for="item in berthList"
                  :key="item.id"
                  :label="item.code"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="title == '添加泊位二维码'">
          <el-col :span="24">
            <el-form-item label="机构" prop="departmentId">
              <el-select v-model="form.departmentId" placeholder="请选择">
                <el-option
                  v-for="item in departmentList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="数量" prop="count">
              <el-input-number :min="1" v-model="form.count" :step="1" step-strictly></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="title == '添加泊位二维码'" :loading="btLodding" @click="submitForm('export')">新增并导出</el-button>
        <el-button type="primary" v-if="title != '查看二维码'" :loading="btLodding" @click="submitForm()">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!--导出列表对话框 -->
    <el-dialog :close-on-click-modal="false" title="导出列表" :visible.sync="exportOpen" width="1000px" append-to-body>
      <el-button
        size="mini"
        type="primary"
        plain
        @click="getExportList()"
      >刷新
      </el-button>
      <el-table v-loading="exportLoading" :data="exportList" >
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="名称"  align="center"  prop="name"/>
        <el-table-column label="状态" align="center">
          <template slot-scope="{row}">
            <dict-tag :options="dict.type.EExportRecordStatus" :value="row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="文件类型" align="center">
          <template slot-scope="{row}">
            <dict-tag :options="dict.type.EExportRecordType" :value="row.type"/>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button
              v-if="row.status == 2"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleExportDown(row)"
              v-hasPermi="['system:spcartype:edit']"
            >下载</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="exportTotal>0"
        :total="exportTotal"
        :page.sync="exportParams.page"
        :limit.sync="exportParams.pageSize"
        @pagination="getExportList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="exportOpen = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {fetchList, berthQrcodeAdd, unbindBerth, bindBerth,exportList,berthQrcodeExport} from "@/api/park/qrcode";
import { getDepartmentList } from '@/api/base'
import { listAuthBerth } from '@/api/park/berth'
import { getToken, TokenKey } from '@/utils/auth'
import QRCode from 'qrcodejs2'
export default {
  name: "qrcode",
  dicts: ['EBerthQrcodeStatus','EExportRecordStatus','EExportRecordType'],
  components:{},
  data() {
    return {
      tableList:[
        {label:'机构名称',prop:'departmentName',},
        {label:'片区名称',prop:'parkLotName',},
        {label:'泊位编码',prop:'berthCode',},
        {label:'编码',prop:'code',},
        {label:'链接',prop:'url',},
        {label:'状态',prop:'status',},
        {label:'创建者',prop:'createBy',},
        {label:'创建时间',prop:'createTime',},
      ],//表格字段显示
      //片区数据
      areaList: [],
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车位信息表格数据
      spparkplaceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        berthId: [
          {required: true, message: "泊位不能为空", trigger: "change"}
        ],
        departmentId: [
          {required: true, message: "机构不能为空", trigger: "change"}
        ],
        count: [
          {required: true, message: "数量不能为空", trigger: "blur"}
        ],
      },
      departmentList: [],//机构数据
      // 查询参数
      bwqueryParams: {
        page: 1,
        pageSize: 30
      },
      berthList:[],//泊位数据
      bwTotal:0,//泊位列表总数
      bwLoddng:false,//泊位表格加载
      exportParams:{//导出列表请求参数
        page: 1,
        pageSize: 10,
      },
      exportTotal:0,//导出列表总数
      exportList:[],//导出列表数据
      exportOpen:false,//导出弹窗开启
      exportLoading:false,//导出表格加载
      ExportFlag:false,//导出
      btLodding:false,
    };
  },
  created() {
    this.getDepartmentList();
    this.getList();
  },
  methods: {
    handleExportDown(row){
      const xhr = new XMLHttpRequest()
      // xhr.responseType = "blob";
      xhr.open('get', row.path, true);
      xhr.responseType = 'blob';
      xhr.setRequestHeader(TokenKey,getToken())
      xhr.send()
      xhr.onload = async (res) => {
        if (xhr.readyState === 4 && xhr.status === 200) {
          this.xiazia(xhr.response,row.path)
        }else{
          this.$u.toast('系统错误请联系管理员~');
        }
      }
    },
    xiazia(response,path){//下载文件资源
      var blob = new Blob([response], {
        type: 'multipart/form-data'
      }); // applicationnd.openxmlformats-officedocument.wordprocessingml.document这里表示doc类型
      var downloadElement = document.createElement('a');
      var href = window.URL.createObjectURL(blob); // 创建下载的链接
      downloadElement.style.display = 'none';
      downloadElement.href = href;
      let link = path.split('/')
      downloadElement.download = link[link.length - 1]; // 下载后文件名
      document.body.appendChild(downloadElement);
      downloadElement.click(); // 点击下载
      document.body.removeChild(downloadElement); // 下载完成移除元素
      window.URL.revokeObjectURL(href); // 释放掉blob对象
    },
    //查看导出列表
    handleExportList(){
      this.exportOpen = true
      this.exportParams.page = 1
      this.getExportList()
    },
    async getExportList(){//导出列表
      this.exportLoading = true
      let response = await exportList(this.exportParams)
      let data = response.data || {}
      let rows = data.list || []
      this.exportList = rows
      this.exportTotal = data.total || 0;
      this.exportLoading = false
    },
    //滚动加载更多方法
    loadMore(){
      if(this.berthList.length == this.bwTotal) return
      this.bwqueryParams.page+=1
      this.listAuthBerth()
    },
    remoteMethod(e){//下拉远程搜索
      this.bwqueryParams.code = e
      this.bwqueryParams.page = 1
      this.berthList = []
      this.listAuthBerth()
    },
    async listAuthBerth(){//当前用户已授权的片区的泊位分页列表
      this.bwLoddng = true
      let response = await listAuthBerth(this.bwqueryParams)
      let data = response.data || {}
      let rows = data.list || []
      this.berthList = rows
      this.bwTotal = data.total || 0;
      this.bwLoddng = false
    },
    handleBind(row){//绑定按钮
      this.reset()
      this.open = true;
      this.title = "关联车位号";
      this.form.id = row.id
      this.bwqueryParams.departmentId = row.departmentId
      this.listAuthBerth()
    },
    //解绑按钮
    handleUnbind(row) {
      const id = row.id
      this.$modal.confirm('是否确认解绑泊位？').then(function() {
        return unbindBerth({id});
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    //查看二维码
    handleEwmShow(row) {
      this.open = true;
      this.title = "查看二维码";
      //dom节点渲染成功后再执行生成二维码方法
      this.$nextTick(function() {
        document.getElementById('qrcode').innerHTML = ''
        new QRCode('qrcode', {
          width: 250,
          height: 250,
          text: row.url,
          colorDark: '#ffffff',
          colorLight: '#000000',
          correctLevel: QRCode.CorrectLevel.H
        })
      })
    },
    getDepartmentList(){//获取机构
      getDepartmentList().then(res => {
        this.departmentList = res.data || []
      })
    },
    /** 查询车位信息列表 */
    getList() {
      this.loading = true;
      fetchList(this.queryParams).then(response => {
        let data = response.data || {}
        let rows = data.list || []
        this.spparkplaceList = rows.map(item=>{
          let parkNameList = item.parkNameList || []
          return {
            ...item,
            parkNameStr:parkNameList.toString()
          }
        });
        this.total = data.total || 0;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true;
      this.title = "添加泊位二维码";
      this.getDepartmentList();
    },
    /** 提交按钮 */
    submitForm(type) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.btLodding = true
          if(this.title == "关联车位号") {
            bindBerth(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.getList()
              this.open = false
              this.btLodding = false
            }).catch(e=>this.btLodding = false)
          }else if(this.title == "添加泊位二维码"){
            this.form.exportFlag = type ? true : false
            berthQrcodeAdd(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.getList()
              this.open = false
              this.btLodding = false
              if(type) {
                this.exportOpen = true
                this.exportParams.page = 1
                this.getExportList()
              }
            }).catch(e=>this.btLodding = false)
          }
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      if(this.ExportFlag) return
      this.ExportFlag = true
      let formData = {}
      // formData.append('departmentId',this.queryParams.departmentId)
      if(this.queryParams.departmentId) formData.departmentId = this.queryParams.departmentId
      if(this.queryParams.code) formData.code = this.queryParams.code
      berthQrcodeExport(formData).then(response => {
        let resultCode = response.resultCode
        this.ExportFlag = false
        this.exportOpen = true
        this.getExportList()
        if(resultCode == 0)  this.$modal.msgSuccess("导出成功，请点击导出列表查看进度");
      }).catch(()=>{this.ExportFlag = false});
    },
  }
};
</script>
<style lang="scss">
#qrcode{
  width: 250px;
  margin: 0 auto;
}
#container {width:650px; height: 300px; }
</style>
